<template>
	<view class="container">
		<view class="form">
			<view class="form-section">
				<view class="section-title">基本信息</view>
				<view class="form-item">
					<text class="label">设备名称 *</text>
					<input class="input" v-model="formData.deviceName" placeholder="请输入设备名称" />
				</view>
				<view class="form-item">
					<text class="label">设备编号 *</text>
					<input class="input" v-model="formData.deviceCode" placeholder="请输入设备编号" />
				</view>
				<view class="form-item">
					<text class="label">设备类型 *</text>
					<picker @change="onDeviceTypeChange" :value="deviceTypeIndex" :range="deviceTypes">
						<view class="picker">
							{{ formData.deviceType || '请选择设备类型' }}
						</view>
					</picker>
				</view>
				<view class="form-item">
					<text class="label">制造商</text>
					<input class="input" v-model="formData.manufacturer" placeholder="请输入制造商" />
				</view>
			</view>

			<view class="form-section">
				<view class="section-title">位置信息</view>
				<view class="form-item">
					<text class="label">安装位置 *</text>
					<input class="input" v-model="formData.installLocation" placeholder="请输入安装位置" />
				</view>
				<view class="form-item">
					<text class="label">经度</text>
					<input class="input" v-model="formData.longitude" placeholder="请输入经度" type="digit" />
				</view>
				<view class="form-item">
					<text class="label">纬度</text>
					<input class="input" v-model="formData.latitude" placeholder="请输入纬度" type="digit" />
				</view>
			</view>

			<view class="form-section">
				<view class="section-title">负责人信息</view>
				<view class="form-item">
					<text class="label">负责人</text>
					<input class="input" v-model="formData.responsiblePerson" placeholder="请输入负责人姓名" />
				</view>
				<view class="form-item">
					<text class="label">联系电话</text>
					<input class="input" v-model="formData.contactPhone" placeholder="请输入联系电话" />
				</view>
				<view class="form-item">
					<text class="label">安装时间</text>
					<picker mode="date" @change="onInstallTimeChange" :value="formData.installTime">
						<view class="picker">
							{{ formData.installTime || '请选择安装时间' }}
						</view>
					</picker>
				</view>
			</view>

			<view class="form-section">
				<view class="section-title">设备状态</view>
				<view class="form-item">
					<text class="label">设备状态</text>
					<picker @change="onStatusChange" :value="statusIndex" :range="statusOptions">
						<view class="picker">
							{{ statusOptions[statusIndex] }}
						</view>
					</picker>
				</view>
			</view>
		</view>

		<view class="actions">
			<button class="btn-cancel" @click="cancel">取消</button>
			<button class="btn-submit" @click="submit" :disabled="submitting">
				{{ submitting ? '提交中...' : (isEdit ? '更新' : '创建') }}
			</button>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { createDevice, updateDevice, getDeviceDetail } from '@/api/device.js'
import { useDeviceStore } from '@/stores/device.js'

const deviceStore = useDeviceStore()
const submitting = ref(false)
const isEdit = ref(false)
const deviceTypeIndex = ref(0)
const statusIndex = ref(0)

const deviceTypes = ['水质监测仪', '流量计', '压力传感器', '温度传感器', 'pH计', '溶解氧仪', '浊度计', '其他']

const statusOptions = ['在线', '离线', '故障']

const formData = ref({
	deviceName: '',
	deviceCode: '',
	deviceType: '',
	manufacturer: '',
	installLocation: '',
	longitude: '',
	latitude: '',
	responsiblePerson: '',
	contactPhone: '',
	installTime: '',
	status: 1 // 默认在线
})

// 设备类型选择
const onDeviceTypeChange = (e) => {
	deviceTypeIndex.value = e.detail.value
	formData.value.deviceType = deviceTypes[e.detail.value]
}

// 安装时间选择
const onInstallTimeChange = (e) => {
	formData.value.installTime = e.detail.value
}

// 状态选择
const onStatusChange = (e) => {
	statusIndex.value = e.detail.value
	formData.value.status = parseInt(e.detail.value) + 1
}

// 获取设备详情（编辑模式）
const fetchDetail = async () => {
	try {
		const pages = getCurrentPages()
		const currentPage = pages[pages.length - 1]
		const deviceId = currentPage.options?.deviceId
		const mode = currentPage.options?.mode
		
		if (deviceId && mode === 'edit') {
			isEdit.value = true
			uni.showLoading({ title: '加载中...' })
			
			const res = await getDeviceDetail(deviceId)
			if (res && res.code === 200) {
				const device = res.obj
				formData.value = {
					deviceId: device.deviceId,
					deviceName: device.deviceName || '',
					deviceCode: device.deviceCode || '',
					deviceType: device.deviceType || '',
					manufacturer: device.manufacturer || '',
					installLocation: device.installLocation || '',
					longitude: device.longitude ? String(device.longitude) : '',
					latitude: device.latitude ? String(device.latitude) : '',
					responsiblePerson: device.responsiblePerson || '',
					contactPhone: device.contactPhone || '',
					installTime: device.installTime ? device.installTime.split(' ')[0] : '',
					status: device.status || 1
				}
				
				// 设置选择器索引
				const typeIndex = deviceTypes.findIndex(type => type === device.deviceType)
				deviceTypeIndex.value = typeIndex >= 0 ? typeIndex : 0
				statusIndex.value = (device.status || 1) - 1
			} else {
				uni.showToast({
					title: res?.msg || '获取设备信息失败',
					icon: 'none'
				})
			}
		}
	} catch (error) {
		console.error('获取设备详情失败:', error)
		uni.showToast({
			title: '获取设备信息失败',
			icon: 'none'
		})
	} finally {
		uni.hideLoading()
	}
}

// 表单验证
const validateForm = () => {
	if (!formData.value.deviceName.trim()) {
		uni.showToast({ title: '请输入设备名称', icon: 'none' })
		return false
	}
	if (!formData.value.deviceCode.trim()) {
		uni.showToast({ title: '请输入设备编号', icon: 'none' })
		return false
	}
	if (!formData.value.deviceType) {
		uni.showToast({ title: '请选择设备类型', icon: 'none' })
		return false
	}
	if (!formData.value.installLocation.trim()) {
		uni.showToast({ title: '请输入安装位置', icon: 'none' })
		return false
	}
	
	// 验证经纬度格式
	if (formData.value.longitude && formData.value.longitude.trim()) {
		const lng = parseFloat(formData.value.longitude)
		if (isNaN(lng) || lng < -180 || lng > 180) {
			uni.showToast({ title: '经度格式不正确（-180到180之间）', icon: 'none' })
			return false
		}
	}
	
	if (formData.value.latitude && formData.value.latitude.trim()) {
		const lat = parseFloat(formData.value.latitude)
		if (isNaN(lat) || lat < -90 || lat > 90) {
			uni.showToast({ title: '纬度格式不正确（-90到90之间）', icon: 'none' })
			return false
		}
	}
	
	// 验证手机号格式
	if (formData.value.contactPhone && formData.value.contactPhone.trim()) {
		const phoneRegex = /^1[3-9]\d{9}$/
		if (!phoneRegex.test(formData.value.contactPhone)) {
			uni.showToast({ title: '请输入正确的手机号码', icon: 'none' })
			return false
		}
	}
	
	return true
}

// 提交表单
const submit = async () => {
	if (!validateForm()) return
	
	try {
		submitting.value = true
		uni.showLoading({ title: isEdit.value ? '更新中...' : '创建中...' })
		
		// 处理数据格式
		const submitData = {
			...formData.value,
			// 确保经纬度是数字类型，如果为空则设为null
			longitude: formData.value.longitude && formData.value.longitude.trim() 
				? parseFloat(formData.value.longitude) 
				: null,
			latitude: formData.value.latitude && formData.value.latitude.trim() 
				? parseFloat(formData.value.latitude) 
				: null,
			// 处理安装时间，确保格式正确
			installTime: formData.value.installTime 
				? new Date(formData.value.installTime + ' 00:00:00') 
				: null,
			// 确保状态是数字类型
			status: parseInt(formData.value.status) || 1
		}
		
		// 移除空字符串字段，避免后端验证失败
		Object.keys(submitData).forEach(key => {
			if (submitData[key] === '' || submitData[key] === undefined) {
				delete submitData[key]
			}
		})
		
		console.log('提交的数据:', submitData)
		
		const res = isEdit.value 
			? await updateDevice(submitData)
			: await createDevice(submitData)
			
		console.log('提交响应:', res)
		
		if (res && res.code === 200) {
			uni.showToast({
				title: isEdit.value ? '更新成功' : '创建成功',
				icon: 'success'
			})
			
			// 如果是编辑模式，设置更新标志
			if (isEdit.value) {
				// 将更新后的设备信息存储到store中
				deviceStore.setCurrentDevice(res.obj)
				// 设置页面需要刷新的标志
				uni.setStorageSync('device_updated', true)
			}
			
			setTimeout(() => {
				uni.navigateBack()
			}, 1500)
		} else {
			uni.showToast({
				title: res?.msg || (isEdit.value ? '更新失败' : '创建失败'),
				icon: 'none'
			})
		}
	} catch (error) {
		console.error('提交失败:', error)
		
		// 根据错误类型显示不同的提示
		let errorMessage = '网络错误，请重试'
		
		if (error.statusCode === 500) {
			errorMessage = '服务器内部错误，请检查数据格式'
		} else if (error.statusCode === 400) {
			errorMessage = '请求参数错误，请检查必填字段'
		} else if (error.statusCode === 401) {
			errorMessage = '未授权，请重新登录'
		} else if (error.errMsg && error.errMsg.includes('timeout')) {
			errorMessage = '请求超时，请重试'
		}
		
		uni.showModal({
			title: '创建失败',
			content: errorMessage + '\n\n错误详情：' + JSON.stringify(error),
			showCancel: false
		})
	} finally {
		submitting.value = false
		uni.hideLoading()
	}
}

// 取消
const cancel = () => {
	uni.navigateBack()
}

onMounted(() => {
	fetchDetail()
})
</script>

<style lang="scss" scoped>
.container {
	padding: 20rpx;
	background: #f8fffe;
	min-height: 100vh;
	padding-bottom: 120rpx;
}

.form-section {
	margin-bottom: 30rpx;
}

.section-title {
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 20rpx;
	padding-left: 10rpx;
	border-left: 6rpx solid #2E7D32;
}

.form-item {
	background: #ffffff;
	border: 2rpx solid #e8f5e8;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(46, 125, 50, 0.1);
}

.label {
	font-size: 26rpx;
	color: #333;
	font-weight: 500;
	margin-bottom: 15rpx;
	display: block;
}

.input {
	width: 100%;
	height: 60rpx;
	font-size: 26rpx;
	color: #333;
	border: none;
	background: transparent;
}

.picker {
	height: 60rpx;
	line-height: 60rpx;
	font-size: 26rpx;
	color: #333;
}

.actions {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background: #ffffff;
	padding: 20rpx;
	border-top: 1rpx solid #e8f5e8;
	display: flex;
	gap: 20rpx;
}

.btn-cancel, .btn-submit {
	flex: 1;
	height: 80rpx;
	border-radius: 10rpx;
	font-size: 26rpx;
	border: none;
}

.btn-cancel {
	background-color: #f8f9fa;
	color: #333;
	border: 1rpx solid #ddd;
}

.btn-submit {
	background-color: #2E7D32;
	color: #ffffff;
	
	&:disabled {
		background-color: #ccc;
	}
}
</style>
